package com.sy.auth.utils;

import com.sy.model.system.SysMenu;

import java.util.ArrayList;
import java.util.List;

public class MenuHelper {
    public static List<SysMenu> buildTree(List<SysMenu> sysMenuList) {
        // 结果
        List<SysMenu> trees = new ArrayList<>();

        // 遍历列表，对第一层的菜单元素进行递归 parentId = 0
        for (SysMenu sysMenu : sysMenuList){
            if(sysMenu.getParentId().longValue() == 0){
                trees.add(getChildren(sysMenu, sysMenuList));
            }
        }

        return trees;
    }

    private static SysMenu getChildren(SysMenu sysMenu, List<SysMenu> sysMenuList) {

        List<SysMenu> children = new ArrayList<>();
        // 当前节点的id = 下一层节点的parentId
        for (SysMenu menu : sysMenuList){
            if(menu.getParentId().longValue() == sysMenu.getId()){
                children.add(getChildren(menu, sysMenuList));
            }
        }
        sysMenu.setChildren(children);
        return sysMenu;
    }
}
